package com.yeskery.nut.core;

import com.yeskery.nut.application.NutApplication;
import com.yeskery.nut.bean.ApplicationContext;
import com.yeskery.nut.plugin.*;

import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 基于应用上下文的插件初始化器
 * @author Yeskery
 * 2023/7/24
 */
public class ApplicationContextPluginInitializer extends BasePluginInitializer {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(ApplicationContextPluginInitializer.class.getName());

    /** 应用上下文对象 */
    private final ApplicationContext applicationContext;

    /**
     * 构建基于应用上下文的插件初始化器
     * @param applicationContext 应用上下文对象
     */
    public ApplicationContextPluginInitializer(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    protected Collection<Plugin> getPlugins() {
        return applicationContext.getBeans(Plugin.class);
    }

    @Override
    protected void beforeExecutePluginBindMethod(NutApplication nutApplication, BindContext bindContext, Plugin plugin) {
        // 绑定NutApplication支持插件
        if (plugin instanceof NutApplicationSupportBasePlugin) {
            ((NutApplicationSupportBasePlugin) plugin).setNutApplication(nutApplication);
        }
        if (plugin instanceof ApplicationContextPluginPostProcessor) {
            try {
                ((ApplicationContextPluginPostProcessor) plugin).process(applicationContext);
            } catch (Exception e) {
                logger.logp(Level.SEVERE, plugin.getClass().getName(), "process",
                        "ApplicationContextPluginPostProcessor class [" + plugin.getClass().getName() + "] Execute Fail", e);
            }
        }
    }
}
